# 增强的系统管理功能模块
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q, Count, Sum, Avg
from django.http import JsonResponse, HttpResponse
from django.utils import timezone
from django.views.decorators.http import require_http_methods, require_POST
from django.views.decorators.csrf import csrf_exempt
from django.core.management import call_command
from django.conf import settings
import json
import os
import psutil
import platform
from datetime import datetime, timedelta
from io import StringIO
import subprocess
import logging

from .models import AssetLog, Asset
from .models_system import SystemLog, SystemParameter, DataBackup, SystemNotification


logger = logging.getLogger(__name__)


@login_required
@permission_required('auth.change_user', raise_exception=True)
def system_dashboard(request):
    """系统管理仪表板"""
    # 系统健康状态
    health_status = get_system_health_status()
    
    # 最近的系统日志
    recent_logs = SystemLog.objects.select_related('user').order_by('-created_at')[:10]
    
    # 系统统计信息
    system_stats = get_system_statistics()
    
    # 存储使用情况
    storage_info = get_storage_info()
    
    # 数据库统计
    database_stats = get_database_statistics()
    
    context = {
        'health_status': health_status,
        'recent_logs': recent_logs,
        'system_stats': system_stats,
        'storage_info': storage_info,
        'database_stats': database_stats,
    }
    
    return render(request, 'assets/system/dashboard.html', context)


def get_system_health_status():
    """获取系统健康状态"""
    try:
        # CPU使用率
        cpu_percent = psutil.cpu_percent(interval=1)
        
        # 内存使用情况
        memory = psutil.virtual_memory()
        memory_percent = memory.percent
        
        # 磁盘使用情况
        disk = psutil.disk_usage('/')
        disk_percent = (disk.used / disk.total) * 100
        
        # 系统负载
        load_avg = os.getloadavg() if hasattr(os, 'getloadavg') else (0, 0, 0)
        
        # 运行时间
        boot_time = psutil.boot_time()
        uptime = datetime.now() - datetime.fromtimestamp(boot_time)
        
        # 网络连接数
        connections = len(psutil.net_connections())
        
        # 进程数
        process_count = len(psutil.pids())
        
        # 系统健康评分
        health_score = calculate_health_score(cpu_percent, memory_percent, disk_percent)
        
        return {
            'cpu_percent': round(cpu_percent, 2),
            'memory_percent': round(memory_percent, 2),
            'memory_total': round(memory.total / (1024**3), 2),  # GB
            'memory_used': round(memory.used / (1024**3), 2),   # GB
            'disk_percent': round(disk_percent, 2),
            'disk_total': round(disk.total / (1024**3), 2),     # GB
            'disk_used': round(disk.used / (1024**3), 2),       # GB
            'load_avg': load_avg,
            'uptime_days': uptime.days,
            'uptime_hours': uptime.seconds // 3600,
            'connections': connections,
            'process_count': process_count,
            'health_score': health_score,
            'status': get_health_status_text(health_score)
        }
    except Exception as e:
        logger.error(f"获取系统健康状态失败: {e}")
        return {
            'error': '无法获取系统健康状态',
            'health_score': 0,
            'status': 'unknown'
        }


def calculate_health_score(cpu_percent, memory_percent, disk_percent):
    """计算系统健康评分"""
    # 基础分数100分
    score = 100
    
    # CPU使用率扣分
    if cpu_percent > 80:
        score -= 30
    elif cpu_percent > 60:
        score -= 20
    elif cpu_percent > 40:
        score -= 10
    
    # 内存使用率扣分
    if memory_percent > 90:
        score -= 30
    elif memory_percent > 80:
        score -= 20
    elif memory_percent > 70:
        score -= 10
    
    # 磁盘使用率扣分
    if disk_percent > 95:
        score -= 25
    elif disk_percent > 85:
        score -= 15
    elif disk_percent > 75:
        score -= 5
    
    return max(0, score)


def get_health_status_text(score):
    """根据健康评分获取状态文本"""
    if score >= 90:
        return 'excellent'
    elif score >= 80:
        return 'good'
    elif score >= 70:
        return 'fair'
    elif score >= 60:
        return 'poor'
    else:
        return 'critical'


def get_system_statistics():
    """获取系统统计信息"""
    today = timezone.now().date()
    week_ago = today - timedelta(days=7)
    
    return {
        'platform': platform.platform(),
        'python_version': platform.python_version(),
        'django_version': getattr(settings, 'DJANGO_VERSION', 'Unknown'),
        'total_users': Asset.objects.values('user').distinct().count(),
        'total_assets': Asset.objects.count(),
        'today_operations': AssetLog.objects.filter(created_at__date=today).count(),
        'week_operations': AssetLog.objects.filter(created_at__date__gte=week_ago).count(),
        'error_logs_today': SystemLog.objects.filter(
            level='ERROR',
            created_at__date=today
        ).count(),
    }


def get_storage_info():
    """获取存储信息"""
    try:
        # 媒体文件存储
        media_root = getattr(settings, 'MEDIA_ROOT', '')
        if media_root and os.path.exists(media_root):
            media_size = get_directory_size(media_root)
        else:
            media_size = 0
        
        # 静态文件存储
        static_root = getattr(settings, 'STATIC_ROOT', '')
        if static_root and os.path.exists(static_root):
            static_size = get_directory_size(static_root)
        else:
            static_size = 0
        
        # 日志文件大小
        log_size = get_log_files_size()
        
        return {
            'media_size_mb': round(media_size / (1024**2), 2),
            'static_size_mb': round(static_size / (1024**2), 2),
            'log_size_mb': round(log_size / (1024**2), 2),
            'total_size_mb': round((media_size + static_size + log_size) / (1024**2), 2)
        }
    except Exception as e:
        logger.error(f"获取存储信息失败: {e}")
        return {
            'media_size_mb': 0,
            'static_size_mb': 0,
            'log_size_mb': 0,
            'total_size_mb': 0,
            'error': str(e)
        }


def get_directory_size(path):
    """获取目录大小"""
    total_size = 0
    try:
        for dirpath, dirnames, filenames in os.walk(path):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                if os.path.exists(filepath):
                    total_size += os.path.getsize(filepath)
    except Exception as e:
        logger.error(f"计算目录大小失败 {path}: {e}")
    return total_size


def get_log_files_size():
    """获取日志文件大小"""
    log_size = 0
    try:
        # 查找常见的日志文件位置
        log_paths = [
            '/var/log/',
            'logs/',
            'log/',
        ]
        
        for log_path in log_paths:
            if os.path.exists(log_path):
                log_size += get_directory_size(log_path)
    except Exception as e:
        logger.error(f"计算日志文件大小失败: {e}")
    
    return log_size


def get_database_statistics():
    """获取数据库统计信息"""
    from django.db import connection
    
    try:
        with connection.cursor() as cursor:
            # 获取数据库大小（MySQL）
            if connection.vendor == 'mysql':
                cursor.execute("""
                    SELECT 
                        ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'DB Size in MB'
                    FROM information_schema.tables 
                    WHERE table_schema = %s
                """, [connection.settings_dict['NAME']])
                db_size = cursor.fetchone()[0] or 0
                
                # 获取表统计信息
                cursor.execute("""
                    SELECT 
                        table_name,
                        table_rows,
                        ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'Size in MB'
                    FROM information_schema.tables 
                    WHERE table_schema = %s
                    ORDER BY (data_length + index_length) DESC
                    LIMIT 10
                """, [connection.settings_dict['NAME']])
                table_stats = cursor.fetchall()
            else:
                # SQLite 或其他数据库
                db_size = 0
                table_stats = []
        
        return {
            'db_size_mb': db_size,
            'table_stats': [
                {
                    'table_name': stat[0],
                    'row_count': stat[1],
                    'size_mb': stat[2]
                } for stat in table_stats
            ]
        }
    except Exception as e:
        logger.error(f"获取数据库统计失败: {e}")
        return {
            'db_size_mb': 0,
            'table_stats': [],
            'error': str(e)
        }


@login_required
@permission_required('auth.change_user', raise_exception=True)
def system_performance_monitor(request):
    """系统性能监控"""
    # 获取性能历史数据
    performance_history = get_performance_history()
    
    # 获取当前性能指标
    current_metrics = get_current_performance_metrics()
    
    # 获取性能警告
    performance_warnings = get_performance_warnings()
    
    context = {
        'performance_history': json.dumps(performance_history),
        'current_metrics': current_metrics,
        'performance_warnings': performance_warnings,
    }
    
    return render(request, 'assets/system/performance_monitor.html', context)


def get_performance_history():
    """获取性能历史数据"""
    # 获取最近24小时的性能数据
    history = []
    now = timezone.now()
    
    for i in range(24):
        timestamp = now - timedelta(hours=i)
        
        # 模拟性能数据（实际应用中应该从数据库或监控系统获取）
        try:
            cpu_percent = psutil.cpu_percent()
            memory_percent = psutil.virtual_memory().percent
            
            history.append({
                'timestamp': timestamp.isoformat(),
                'cpu_percent': cpu_percent,
                'memory_percent': memory_percent,
                'response_time': get_average_response_time(timestamp),
                'active_users': get_active_users_count(timestamp)
            })
        except Exception as e:
            logger.error(f"获取性能历史数据失败: {e}")
    
    return list(reversed(history))


def get_current_performance_metrics():
    """获取当前性能指标"""
    try:
        # API响应时间
        avg_response_time = get_average_api_response_time()
        
        # 数据库查询性能
        db_performance = get_database_performance()
        
        # 并发用户数
        concurrent_users = get_concurrent_users()
        
        # 错误率
        error_rate = get_error_rate()
        
        return {
            'avg_response_time': avg_response_time,
            'db_query_time': db_performance.get('avg_query_time', 0),
            'concurrent_users': concurrent_users,
            'error_rate': error_rate,
            'throughput': get_throughput(),
        }
    except Exception as e:
        logger.error(f"获取当前性能指标失败: {e}")
        return {
            'avg_response_time': 0,
            'db_query_time': 0,
            'concurrent_users': 0,
            'error_rate': 0,
            'throughput': 0,
        }


def get_average_response_time(timestamp=None):
    """获取平均响应时间"""
    # 这里应该从实际的性能监控数据中获取
    # 暂时返回模拟数据
    import random
    return round(random.uniform(100, 500), 2)


def get_active_users_count(timestamp=None):
    """获取活跃用户数"""
    if timestamp:
        # 获取指定时间的活跃用户数
        hour_ago = timestamp - timedelta(hours=1)
        return AssetLog.objects.filter(
            created_at__range=[hour_ago, timestamp]
        ).values('operator').distinct().count()
    else:
        # 获取当前活跃用户数
        hour_ago = timezone.now() - timedelta(hours=1)
        return AssetLog.objects.filter(
            created_at__gte=hour_ago
        ).values('operator').distinct().count()


def get_average_api_response_time():
    """获取API平均响应时间"""
    # 这里应该从API监控数据中获取
    # 暂时返回模拟数据
    return 150.5


def get_database_performance():
    """获取数据库性能指标"""
    from django.db import connection
    
    try:
        with connection.cursor() as cursor:
            if connection.vendor == 'mysql':
                # 获取MySQL性能指标
                cursor.execute("SHOW STATUS LIKE 'Queries'")
                queries = cursor.fetchone()
                
                cursor.execute("SHOW STATUS LIKE 'Uptime'")
                uptime = cursor.fetchone()
                
                if queries and uptime:
                    qps = int(queries[1]) / int(uptime[1])  # 每秒查询数
                    return {
                        'queries_per_second': round(qps, 2),
                        'avg_query_time': round(1000 / qps, 2) if qps > 0 else 0  # 毫秒
                    }
        
        return {'queries_per_second': 0, 'avg_query_time': 0}
    except Exception as e:
        logger.error(f"获取数据库性能失败: {e}")
        return {'queries_per_second': 0, 'avg_query_time': 0}


def get_concurrent_users():
    """获取并发用户数"""
    # 获取最近5分钟内有操作的用户数
    five_minutes_ago = timezone.now() - timedelta(minutes=5)
    return AssetLog.objects.filter(
        created_at__gte=five_minutes_ago
    ).values('operator').distinct().count()


def get_error_rate():
    """获取错误率"""
    today = timezone.now().date()
    total_operations = AssetLog.objects.filter(created_at__date=today).count()
    error_logs = SystemLog.objects.filter(
        level='ERROR',
        created_at__date=today
    ).count()
    
    if total_operations > 0:
        return round((error_logs / total_operations) * 100, 2)
    return 0


def get_throughput():
    """获取系统吞吐量（每分钟操作数）"""
    one_minute_ago = timezone.now() - timedelta(minutes=1)
    return AssetLog.objects.filter(created_at__gte=one_minute_ago).count()


def get_performance_warnings():
    """获取性能警告"""
    warnings = []
    
    try:
        # CPU使用率警告
        cpu_percent = psutil.cpu_percent()
        if cpu_percent > 80:
            warnings.append({
                'type': 'cpu_high',
                'level': 'critical' if cpu_percent > 90 else 'warning',
                'message': f'CPU使用率过高: {cpu_percent}%',
                'suggestion': '检查是否有异常进程占用CPU资源'
            })
        
        # 内存使用率警告
        memory_percent = psutil.virtual_memory().percent
        if memory_percent > 85:
            warnings.append({
                'type': 'memory_high',
                'level': 'critical' if memory_percent > 95 else 'warning',
                'message': f'内存使用率过高: {memory_percent}%',
                'suggestion': '考虑增加内存或优化内存使用'
            })
        
        # 磁盘空间警告
        disk_percent = (psutil.disk_usage('/').used / psutil.disk_usage('/').total) * 100
        if disk_percent > 85:
            warnings.append({
                'type': 'disk_full',
                'level': 'critical' if disk_percent > 95 else 'warning',
                'message': f'磁盘空间不足: {disk_percent:.1f}%',
                'suggestion': '清理不必要的文件或扩展磁盘空间'
            })
        
        # 错误率警告
        error_rate = get_error_rate()
        if error_rate > 5:
            warnings.append({
                'type': 'error_rate_high',
                'level': 'critical' if error_rate > 10 else 'warning',
                'message': f'系统错误率过高: {error_rate}%',
                'suggestion': '检查系统日志，排查错误原因'
            })
        
    except Exception as e:
        logger.error(f"获取性能警告失败: {e}")
        warnings.append({
            'type': 'monitor_error',
            'level': 'warning',
            'message': '无法获取完整的性能监控数据',
            'suggestion': '检查监控系统是否正常运行'
        })
    
    return warnings


@login_required
@permission_required('auth.change_user', raise_exception=True)
def system_maintenance(request):
    """系统维护"""
    if request.method == 'POST':
        action = request.POST.get('action')
        
        if action == 'clear_cache':
            return clear_system_cache(request)
        elif action == 'cleanup_logs':
            return cleanup_old_logs(request)
        elif action == 'optimize_database':
            return optimize_database(request)
        elif action == 'backup_system':
            return backup_system_data(request)
        elif action == 'check_health':
            return run_health_check(request)
    
    # 获取维护历史
    maintenance_history = get_maintenance_history()
    
    # 获取系统清理建议
    cleanup_suggestions = get_cleanup_suggestions()
    
    context = {
        'maintenance_history': maintenance_history,
        'cleanup_suggestions': cleanup_suggestions,
    }
    
    return render(request, 'assets/system/maintenance.html', context)


def clear_system_cache(request):
    """清理系统缓存"""
    try:
        # 清理Django缓存
        from django.core.cache import cache
        cache.clear()
        
        # 清理会话数据
        from django.contrib.sessions.models import Session
        expired_sessions = Session.objects.filter(expire_date__lt=timezone.now())
        expired_count = expired_sessions.count()
        expired_sessions.delete()
        
        # 记录维护操作
        SystemLog.objects.create(
            user=request.user,
            level='INFO',
            module='MAINTENANCE',
            action='clear_cache',
            message=f'清理系统缓存完成，删除过期会话 {expired_count} 个'
        )
        
        messages.success(request, f'系统缓存清理完成，删除过期会话 {expired_count} 个')
        
    except Exception as e:
        logger.error(f"清理系统缓存失败: {e}")
        messages.error(request, f'清理系统缓存失败: {str(e)}')
    
    return redirect('assets:system_maintenance')


def cleanup_old_logs(request):
    """清理旧日志"""
    try:
        days = int(request.POST.get('days', 30))
        cutoff_date = timezone.now() - timedelta(days=days)
        
        # 清理系统日志
        old_system_logs = SystemLog.objects.filter(created_at__lt=cutoff_date)
        system_log_count = old_system_logs.count()
        old_system_logs.delete()
        
        # 清理资产日志
        old_asset_logs = AssetLog.objects.filter(created_at__lt=cutoff_date)
        asset_log_count = old_asset_logs.count()
        old_asset_logs.delete()
        
        total_deleted = system_log_count + asset_log_count
        
        # 记录维护操作
        SystemLog.objects.create(
            user=request.user,
            level='INFO',
            module='MAINTENANCE',
            action='cleanup_logs',
            message=f'清理 {days} 天前的日志，共删除 {total_deleted} 条记录'
        )
        
        messages.success(request, f'日志清理完成，删除 {total_deleted} 条记录')
        
    except Exception as e:
        logger.error(f"清理旧日志失败: {e}")
        messages.error(request, f'清理旧日志失败: {str(e)}')
    
    return redirect('assets:system_maintenance')


def optimize_database(request):
    """优化数据库"""
    try:
        from django.db import connection
        
        with connection.cursor() as cursor:
            if connection.vendor == 'mysql':
                # MySQL数据库优化
                cursor.execute("SHOW TABLES")
                tables = cursor.fetchall()
                
                optimized_tables = []
                for table in tables:
                    table_name = table[0]
                    cursor.execute(f"OPTIMIZE TABLE {table_name}")
                    optimized_tables.append(table_name)
                
                message = f'数据库优化完成，优化了 {len(optimized_tables)} 个表'
            else:
                # SQLite 数据库优化
                cursor.execute("VACUUM")
                message = 'SQLite数据库优化完成'
        
        # 记录维护操作
        SystemLog.objects.create(
            user=request.user,
            level='INFO',
            module='MAINTENANCE',
            action='optimize_database',
            message=message
        )
        
        messages.success(request, message)
        
    except Exception as e:
        logger.error(f"数据库优化失败: {e}")
        messages.error(request, f'数据库优化失败: {str(e)}')
    
    return redirect('assets:system_maintenance')


def backup_system_data(request):
    """备份系统数据"""
    try:
        # 创建备份记录
        backup = DataBackup.objects.create(
            backup_type='manual',
            created_by=request.user,
            status='in_progress'
        )
        
        # 执行备份
        backup_file = create_database_backup()
        
        if backup_file:
            backup.file_path = backup_file
            backup.file_size = os.path.getsize(backup_file)
            backup.status = 'completed'
            backup.save()
            
            # 记录维护操作
            SystemLog.objects.create(
                user=request.user,
                level='INFO',
                module='MAINTENANCE',
                action='backup_system',
                message=f'系统备份完成: {backup_file}'
            )
            
            messages.success(request, f'系统备份完成: {os.path.basename(backup_file)}')
        else:
            backup.status = 'failed'
            backup.save()
            messages.error(request, '系统备份失败')
        
    except Exception as e:
        logger.error(f"系统备份失败: {e}")
        messages.error(request, f'系统备份失败: {str(e)}')
    
    return redirect('assets:system_maintenance')


def create_database_backup():
    """创建数据库备份"""
    try:
        from django.conf import settings
        from django.core.management import call_command
        
        # 创建备份目录
        backup_dir = os.path.join(settings.BASE_DIR, 'backups')
        os.makedirs(backup_dir, exist_ok=True)
        
        # 生成备份文件名
        timestamp = timezone.now().strftime('%Y%m%d_%H%M%S')
        backup_file = os.path.join(backup_dir, f'backup_{timestamp}.json')
        
        # 执行数据备份
        with open(backup_file, 'w', encoding='utf-8') as f:
            call_command('dumpdata', stdout=f, indent=2)
        
        return backup_file
        
    except Exception as e:
        logger.error(f"创建数据库备份失败: {e}")
        return None


def run_health_check(request):
    """运行系统健康检查"""
    try:
        health_results = perform_comprehensive_health_check()
        
        # 保存健康检查结果
        SystemHealthCheck.objects.create(
            performed_by=request.user,
            results=health_results,
            overall_status=health_results.get('overall_status', 'unknown')
        )
        
        # 记录维护操作
        SystemLog.objects.create(
            user=request.user,
            level='INFO',
            module='MAINTENANCE',
            action='health_check',
            message=f'系统健康检查完成，状态: {health_results.get("overall_status", "unknown")}'
        )
        
        if health_results.get('overall_status') == 'healthy':
            messages.success(request, '系统健康检查完成，系统状态良好')
        else:
            messages.warning(request, '系统健康检查完成，发现一些问题，请查看详细报告')
        
    except Exception as e:
        logger.error(f"系统健康检查失败: {e}")
        messages.error(request, f'系统健康检查失败: {str(e)}')
    
    return redirect('assets:system_maintenance')


def perform_comprehensive_health_check():
    """执行综合健康检查"""
    results = {
        'timestamp': timezone.now().isoformat(),
        'checks': [],
        'warnings': [],
        'errors': []
    }
    
    # 数据库连接检查
    try:
        from django.db import connection
        connection.ensure_connection()
        results['checks'].append({
            'name': '数据库连接',
            'status': 'pass',
            'message': '数据库连接正常'
        })
    except Exception as e:
        results['checks'].append({
            'name': '数据库连接',
            'status': 'fail',
            'message': f'数据库连接失败: {str(e)}'
        })
        results['errors'].append('数据库连接失败')
    
    # 文件系统检查
    try:
        media_root = getattr(settings, 'MEDIA_ROOT', '')
        if media_root and os.path.exists(media_root) and os.access(media_root, os.W_OK):
            results['checks'].append({
                'name': '媒体文件目录',
                'status': 'pass',
                'message': '媒体文件目录可写'
            })
        else:
            results['checks'].append({
                'name': '媒体文件目录',
                'status': 'fail',
                'message': '媒体文件目录不存在或不可写'
            })
            results['errors'].append('媒体文件目录问题')
    except Exception as e:
        results['errors'].append(f'文件系统检查失败: {str(e)}')
    
    # 系统资源检查
    try:
        cpu_percent = psutil.cpu_percent()
        memory_percent = psutil.virtual_memory().percent
        disk_percent = (psutil.disk_usage('/').used / psutil.disk_usage('/').total) * 100
        
        if cpu_percent < 80 and memory_percent < 80 and disk_percent < 85:
            results['checks'].append({
                'name': '系统资源',
                'status': 'pass',
                'message': f'CPU: {cpu_percent}%, 内存: {memory_percent}%, 磁盘: {disk_percent:.1f}%'
            })
        else:
            results['checks'].append({
                'name': '系统资源',
                'status': 'warning',
                'message': f'资源使用率较高 - CPU: {cpu_percent}%, 内存: {memory_percent}%, 磁盘: {disk_percent:.1f}%'
            })
            results['warnings'].append('系统资源使用率较高')
    except Exception as e:
        results['errors'].append(f'系统资源检查失败: {str(e)}')
    
    # 确定整体状态
    if results['errors']:
        results['overall_status'] = 'unhealthy'
    elif results['warnings']:
        results['overall_status'] = 'warning'
    else:
        results['overall_status'] = 'healthy'
    
    return results


def get_maintenance_history():
    """获取维护历史"""
    return SystemLog.objects.filter(
        module='MAINTENANCE'
    ).select_related('user').order_by('-created_at')[:20]


def get_cleanup_suggestions():
    """获取清理建议"""
    suggestions = []
    
    try:
        # 检查旧日志
        old_logs_count = SystemLog.objects.filter(
            created_at__lt=timezone.now() - timedelta(days=30)
        ).count()
        
        if old_logs_count > 1000:
            suggestions.append({
                'type': 'cleanup_logs',
                'priority': 'medium',
                'title': '清理旧日志',
                'description': f'发现 {old_logs_count} 条30天前的日志记录，建议清理以释放存储空间',
                'action': 'cleanup_logs'
            })
        
        # 检查过期会话
        from django.contrib.sessions.models import Session
        expired_sessions = Session.objects.filter(expire_date__lt=timezone.now()).count()
        
        if expired_sessions > 100:
            suggestions.append({
                'type': 'clear_cache',
                'priority': 'low',
                'title': '清理过期会话',
                'description': f'发现 {expired_sessions} 个过期会话，建议清理',
                'action': 'clear_cache'
            })
        
        # 检查磁盘空间
        disk_usage = psutil.disk_usage('/')
        disk_percent = (disk_usage.used / disk_usage.total) * 100
        
        if disk_percent > 80:
            suggestions.append({
                'type': 'disk_cleanup',
                'priority': 'high',
                'title': '磁盘空间不足',
                'description': f'磁盘使用率 {disk_percent:.1f}%，建议清理不必要的文件',
                'action': 'disk_cleanup'
            })
        
    except Exception as e:
        logger.error(f"获取清理建议失败: {e}")
    
    return suggestions


@login_required
@require_POST
def ajax_system_status(request):
    """AJAX获取系统状态"""
    try:
        status = get_system_health_status()
        return JsonResponse({
            'success': True,
            'data': status
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        })


@login_required
@require_POST
def ajax_performance_data(request):
    """AJAX获取性能数据"""
    try:
        metrics = get_current_performance_metrics()
        return JsonResponse({
            'success': True,
            'data': metrics
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        })